# -*-coding:utf8-*-

from bilimonitor import sql
import requests
import json



class Dynamic:
    def __init__(self) -> None:
        self.dynamic_id = None
        #self.send_user_QQ = ''
        self.content = {
            'text':'',
            'pic':[]
        }
        self.type = 0
        pass

    def insertIntoDatabase(self, database:sql.Database):
        '''
        向database中插入动态
        '''
        # 成功返回True
        return database.insertDynamic(self.dynamic_id, self.content)

    def isInDatabase(self, database:sql.Database):
        '''
        判断动态是否在数据库中
        '''
        return database.selectDynamic(self.dynamic_id)
 

 


# 获取动态内容
def getDynamic(uid) -> list:
    '''
    通过uid获取动态
    uid type: str
    rtype: list[Dynamic]
    '''

    res = requests.get('https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history?host_uid='+str(uid)+'offset_dynamic_id=0')
    res.encoding='utf-8'
    res = res.text

    cards_data = json.loads(res)

    '''
    将json转为python对象，转换完成的具体格式为:
    dynamic = {
        code
        msg
        message
        data:{
            has_more
            attenrions:{
                uids:[]
            }
            cards:[
                {
                    desc:{}
                    card:转义后的字符串，原为json
                    extend_json
                    extra:{}
                    display:{}
                },
                ...有12个
            ]
            next_offset
            _gt_
        }
    }

    综上，查询到的所有动态在dynamic['data']['cards']列表中，单个动态的具体内容则在card中（需转义）
    '''


    try:
        all_dynamic = cards_data['data']['cards']
    except:
        print('获取动态出错')
        exit()

    # 存放所有转换后的Dynamic对象
    all_dynamic_list = [] 
    
    # 对所有动态都转为Dynamic对象
    for index in range(len(all_dynamic)):
        dynamic_content = json.loads(all_dynamic[index]['card'])

        
        # 生成动态对象，将动态内容、id、图片等放入对象中
        dynamic = Dynamic()
        #dynamic.content['text'] = dynamic_content['item']['description']
        dynamic.dynamic_id = all_dynamic[index]['desc']['dynamic_id']
        dynamic.type = all_dynamic[index]['desc']['type']
        #dynamic.send_user_QQ = user_qq
        try:
            # 根据动态类型，重新编辑动态内容
            dynamic_type = all_dynamic[index]['desc']['type']
            if dynamic_type == 64:
                # 专栏
                title = dynamic_content['title']
                dynamic.content['text'] = '发布专栏「' + title + '」:\n' + dynamic_content['summary']

                dynamic.content['pic'] = dynamic_content['image_urls']
            elif dynamic_type == 8:
                # 视频
                title = dynamic_content['title']
                dynamic.content['text'] = '发布视频「' + title + '」:\n' + dynamic_content['dynamic']

                dynamic.content['pic'] = [dynamic_content['pic']] # 图片
            elif dynamic_type == 4:
                # 不带图动态
                dynamic.content['text'] = '发布动态:\n' + dynamic_content['item']['content']
            elif dynamic_type == 2:
                # 带图新动态
                dynamic.content['text'] = '发布动态:\n' + dynamic_content['item']['description']

                dynamic.content['pic'] = [i['img_src'] for i in dynamic_content['item']['pictures']] # 里面是一个列表,列表里面每张图片是一个字典，图片链接在img_src里面
            elif dynamic_type == 1:
                # 转发动态
                original_name = dynamic_content['origin_user']['info']['uname']
                dynamic.content['text'] = '转发了「' + original_name + '」的动态:\n' + dynamic_content['item']['content']
                
                # 转发的动态根据源动态的类型，pic的位置不同
                original_dynamic = json.loads(dynamic_content['origin']) #字符串类型的字典，先转为字典再进行操作

                if 'item' in original_dynamic:
                    if 'pictures' in original_dynamic['item']:
                        dynamic.content['pic'] = [i['img_src'] for i in original_dynamic['item']['pictures']]
                    else:
                        pass
                else:
                    dynamic.content['pic'] =[original_dynamic['pic']]
                
            elif dynamic_type == 2048:
                # 应该是活动

                dynamic.content['text'] = '发布活动:\n' + dynamic_content['vest']['content']

                dynamic.content['pic'] = [dynamic_content['sketch']['cover_url']]
            else:
                dynamic.content['text'] = '未知类型动态' + dynamic.type

            dynamic.content['text'] += '\n本条动态地址为'+'https://t.bilibili.com/' + all_dynamic[index]['desc']['dynamic_id_str']
        except:
            dynamic.content['text'] = '此动态出错了'

            pass
        all_dynamic_list.append(dynamic)

    return all_dynamic_list
    



def getAllDynamic(database:sql.Database) -> list:
    '''
    返回当前关注列表中用户的所有新动态
    rtype:list[(user_qq, Dynamic)]
    '''
    # 连接数据库，获取用户关注的字典, 返回{uid:[user_qq...]}
    follow = database.getFollowList()

    # 最后要返回的动态列表
    res = []

    # 对关注列表进行轮询，以uid为key，将同一uid的动态发给不同用户
    for uid in follow:
        dynamic_list = getDynamic(uid)

        # 判断动态是否已有（通过查询数据库中的dynamic表来实现），若是新动态，进行转发之后存入数据库
        for dynamic in dynamic_list:
            if dynamic.isInDatabase(database):
                pass
            else:
                # 先加上发送的名称
                dynamic.content['text'] = database.getUserName(uid) + dynamic.content['text']
                # 向数据库中添加动态
                dynamic.insertIntoDatabase(database)
                # 返回给机器人模块
                for qq in follow[uid]:
                    res.append((qq, dynamic))
    return res



def getLiveStatus(uid) -> tuple:
    '''
    获取直播状态，参数uid为主站id
    返回二元组(直播状态，直播标题)
    '''
    # 先通过主站id获取房间id
    res = requests.get(f'https://api.bilibili.com/x/space/acc/info?mid={str(uid)}&jsonp=jsonp')
    res.encoding = 'utf-8'
    res = res.text
    data = json.loads(res)
    data = data['data']
    roomid = 0
    try:
        roomid = data['live_room']['roomid']
    except:
        pass
    
    
    # 再通过房间id获取对应直播间状态
    res = requests.get('https://api.live.bilibili.com/room/v1/Room/get_info?device=phone&;platform=ios&scale=3&build=10000&room_id=' + str(roomid))
    res.encoding = 'utf-8'
    res = res.text

    try:
        live_data = json.loads(res)
        live_data = live_data['data']
        if str(live_data['live_status']) == '1':
            live_status = True
        else:
            live_status = False
        live_title = live_data['title']
    except:
        live_status = False
        live_title = ''
        pass
    
    return (live_status, live_title)